package com.sunday.authorization.security.authorization.redis.restrict;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 当前用户登录
 *
 * @author sunday
 * @since 2024/8/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ConcurrentUserLogin implements InitializingBean {

    private final StringRedisTemplate stringRedisTemplate;

    private static ConcurrentUserLogin concurrentUserLogin = null;

    @Override
    public void afterPropertiesSet() {
        concurrentUserLogin = this;
    }

    public static ConcurrentUserLogin getInstances() {
        return concurrentUserLogin;
    }

    /**
     * 限制用户同时登录数量，进行 refresh token 适配, 默认实现策略为后踢前
     * @param principalName             账号
     * @param accessToken               访问token
     * @param refreshToken              刷新token
     * @param loginMax                  同时在线数量
     * @param accessExpiresAt           访问token 过期时间/秒
     * @param principalNameExcessAt     账号 生存刷新时间/秒
     */
    public void restriction(String principalName, String accessToken, String refreshToken, int loginMax, long accessExpiresAt, long principalNameExcessAt) {
        stringRedisTemplate.execute(
                RedisScriptLua.RESTRICTION,
                Arrays.asList(principalName, accessToken, refreshToken),
                String.valueOf(loginMax),
                String.valueOf(accessExpiresAt),
                String.valueOf(principalNameExcessAt));
    }
    
}
